<template>
  <el-dialog
    :title="!dataForm.designId ? '新增' : '修改'"
    :close-on-click-modal="false"
    :visible.sync="visible"
    width="80%">
    <el-form :model="dataForm" :rules="dataRule" ref="dataForm" @keyup.enter.native="dataFormSubmit()" label-width="100px">
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="用户ID" prop="userId">
            <el-input v-model="dataForm.userId" placeholder="用户ID"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="草稿ID" prop="draftId">
            <el-input-number v-model="dataForm.draftId" :min="0" placeholder="草稿ID"></el-input-number>
          </el-form-item>
        </el-col>
      </el-row>
      
      <el-form-item label="设计稿名称" prop="designName">
        <el-input v-model="dataForm.designName" placeholder="设计稿名称"></el-input>
      </el-form-item>

      <el-form-item label="缩略图" prop="thumbnailUrl">
        <el-upload
          class="avatar-uploader"
          :action="uploadUrl"
          :show-file-list="false"
          :on-success="handleThumbnailSuccess"
          :before-upload="beforeUpload">
          <img v-if="dataForm.thumbnailUrl" :src="dataForm.thumbnailUrl" class="avatar">
          <i v-else class="el-icon-plus avatar-uploader-icon"></i>
        </el-upload>
      </el-form-item>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="设计稿状态" prop="designStatus">
            <el-radio-group v-model="dataForm.designStatus">
              <el-radio :label="1">正常</el-radio>
              <el-radio :label="2">禁用</el-radio>
              <el-radio :label="3">删除</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="是否公开" prop="isPublic">
            <el-radio-group v-model="dataForm.isPublic">
              <el-radio :label="1">公开</el-radio>
              <el-radio :label="0">私有</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
      </el-row>

      <el-divider content-position="left">基础脸型配置</el-divider>
      
      <el-row :gutter="20">
        <el-col :span="8">
          <el-form-item label="基础脸型ID" prop="faceBaseId">
            <el-input-number v-model="dataForm.faceBaseId" :min="1" placeholder="基础脸型ID"></el-input-number>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="缩放比例" prop="scale">
            <el-input-number v-model="dataForm.scale" :min="0.1" :max="5" :step="0.1" placeholder="缩放比例"></el-input-number>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="旋转角度" prop="rotation">
            <el-input-number v-model="dataForm.rotation" :min="-360" :max="360" :step="1" placeholder="旋转角度"></el-input-number>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="X轴偏移" prop="offsetX">
            <el-input-number v-model="dataForm.offsetX" :step="1" placeholder="X轴偏移"></el-input-number>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="Y轴偏移" prop="offsetY">
            <el-input-number v-model="dataForm.offsetY" :step="1" placeholder="Y轴偏移"></el-input-number>
          </el-form-item>
        </el-col>
      </el-row>

      <el-divider content-position="left">画布配置</el-divider>
      
      <el-row :gutter="20">
        <el-col :span="8">
          <el-form-item label="画布宽度" prop="canvasWidth">
            <el-input-number v-model="dataForm.canvasWidth" :min="100" :max="2000" placeholder="画布宽度"></el-input-number>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="画布高度" prop="canvasHeight">
            <el-input-number v-model="dataForm.canvasHeight" :min="100" :max="2000" placeholder="画布高度"></el-input-number>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="背景颜色" prop="backgroundColor">
            <el-color-picker v-model="dataForm.backgroundColor"></el-color-picker>
          </el-form-item>
        </el-col>
      </el-row>

      <el-form-item label="元数据" prop="metadata">
        <el-input type="textarea" v-model="dataForm.metadata" placeholder='元数据JSON，如：{"version": "1.0", "createdBy": "admin"}'></el-input>
      </el-form-item>
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button @click="visible = false">取消</el-button>
      <el-button type="primary" @click="dataFormSubmit()">确定</el-button>
    </span>
  </el-dialog>
</template>

<script>
export default {
  data () {
    return {
      visible: false,
      uploadUrl: '',
      dataForm: {
        designId: 0,
        userId: '',
        draftId: '',
        designName: '',
        faceBaseId: '',
        thumbnailUrl: '',
        designStatus: 1,
        isPublic: 1,
        scale: 1.0,
        offsetX: 0,
        offsetY: 0,
        rotation: 0,
        canvasWidth: 800,
        canvasHeight: 600,
        backgroundColor: '#FFFFFF',
        metadata: ''
      },
      dataRule: {
        userId: [
          { required: true, message: '用户ID不能为空', trigger: 'blur' }
        ],
        designName: [
          { required: true, message: '设计稿名称不能为空', trigger: 'blur' }
        ],
        faceBaseId: [
          { required: true, message: '基础脸型ID不能为空', trigger: 'blur' }
        ],
        designStatus: [
          { required: true, message: '设计稿状态不能为空', trigger: 'blur' }
        ],
        isPublic: [
          { required: true, message: '是否公开不能为空', trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    init (id) {
      this.dataForm.designId = id || 0
      this.visible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].resetFields()
        if (this.dataForm.designId) {
          this.$http({
            url: this.$http.adornUrl(`/admin/faceDesign/info/${this.dataForm.designId}`),
            method: 'get',
            params: this.$http.adornParams()
          }).then(({ data }) => {
            if (data) {
              this.dataForm.userId = data.userId
              this.dataForm.draftId = data.draftId
              this.dataForm.designName = data.designName
              this.dataForm.faceBaseId = data.featureConfig?.faceBase?.faceBaseId || ''
              this.dataForm.thumbnailUrl = data.thumbnailUrl
              this.dataForm.designStatus = data.designStatus
              this.dataForm.isPublic = data.isPublic
              
              // 基础脸型配置
              if (data.featureConfig?.faceBase) {
                this.dataForm.scale = data.featureConfig.faceBase.scale || 1.0
                this.dataForm.offsetX = data.featureConfig.faceBase.offsetX || 0
                this.dataForm.offsetY = data.featureConfig.faceBase.offsetY || 0
                this.dataForm.rotation = data.featureConfig.faceBase.rotation || 0
              }
              
              // 画布配置
              if (data.featureConfig?.canvas) {
                this.dataForm.canvasWidth = data.featureConfig.canvas.width || 800
                this.dataForm.canvasHeight = data.featureConfig.canvas.height || 600
                this.dataForm.backgroundColor = data.featureConfig.canvas.backgroundColor || '#FFFFFF'
              }
              
              // 元数据
              if (data.featureConfig?.metadata) {
                this.dataForm.metadata = JSON.stringify(data.featureConfig.metadata, null, 2)
              }
            }
          })
        }
      })
    },
    // 表单提交
    dataFormSubmit () {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          // 构建featureConfig
          let featureConfig = {
            faceBase: {
              faceBaseId: this.dataForm.faceBaseId,
              faceName: '基础脸型',
              imageUrl: '',
              faceType: 1,
              scale: this.dataForm.scale,
              offsetX: this.dataForm.offsetX,
              offsetY: this.dataForm.offsetY,
              rotation: this.dataForm.rotation
            },
            features: [],
            canvas: {
              width: this.dataForm.canvasWidth,
              height: this.dataForm.canvasHeight,
              backgroundColor: this.dataForm.backgroundColor
            },
            metadata: {}
          }

          // 解析元数据
          if (this.dataForm.metadata) {
            try {
              featureConfig.metadata = JSON.parse(this.dataForm.metadata)
            } catch (e) {
              featureConfig.metadata = {
                version: '1.0',
                createdBy: this.dataForm.userId
              }
            }
          }

          this.$http({
            url: this.$http.adornUrl(`/admin/faceDesign${!this.dataForm.designId ? '' : ''}`),
            method: !this.dataForm.designId ? 'post' : 'put',
            data: this.$http.adornData({
              'designId': this.dataForm.designId || undefined,
              'userId': this.dataForm.userId,
              'draftId': this.dataForm.draftId,
              'designName': this.dataForm.designName,
              'featureConfig': featureConfig,
              'thumbnailUrl': this.dataForm.thumbnailUrl,
              'designStatus': this.dataForm.designStatus,
              'isPublic': this.dataForm.isPublic
            })
          }).then(({ data }) => {
            this.$message({
              message: '操作成功',
              type: 'success',
              duration: 1500
            })
            this.visible = false
            this.$emit('refreshDataList')
          })
        }
      })
    },
    // 缩略图上传成功
    handleThumbnailSuccess (res, file) {
      this.dataForm.thumbnailUrl = res.url
    },
    // 上传前校验
    beforeUpload (file) {
      const isJPG = file.type === 'image/jpeg'
      const isPNG = file.type === 'image/png'
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isJPG && !isPNG) {
        this.$message.error('上传图片只能是 JPG/PNG 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传图片大小不能超过 2MB!')
      }
      return (isJPG || isPNG) && isLt2M
    }
  }
}
</script>

<style scoped>
.avatar-uploader {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  width: 178px;
  height: 178px;
}
.avatar-uploader:hover {
  border-color: #409EFF;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>